package io.gitee.zhangbinhub.admin.workflow.init

import com.mybatisflex.core.dialect.DbTypeUtil
import io.gitee.zhangbinhub.acp.boot.init.AcpInitialization
import io.gitee.zhangbinhub.admin.common.constant.DbConstant
import io.gitee.zhangbinhub.admin.workflow.constant.WorkFlowConstant
import org.noear.solon.Solon
import org.noear.solon.annotation.Component
import org.noear.solon.annotation.Inject
import org.noear.solon.core.util.ResourceUtil
import org.noear.solon.data.sql.SqlUtils
import javax.sql.DataSource

@Component
open class DataInitialization(
    @param:Inject(DbConstant.DB_DEFAULT) private val sqlUtils: SqlUtils,
    @param:Inject(DbConstant.DB_DEFAULT) private val dataSource: DataSource
) : AcpInitialization {
    override val name: String
        get() = "Data Initialization"

    private fun initTable() {
        ResourceUtil.getResourceAsString(
            "${DbConstant.SCHEMA_PATH}/${
                DbTypeUtil.getDbType(dataSource).name.lowercase()
            }/${DbConstant.SCHEMA_FILE}"
        )?.apply {
            for (sql in this.split(";")) {
                if (sql.trim { it <= ' ' }.length > 10) {
                    sqlUtils.sql(sql).update()
                }
            }
        }
        ResourceUtil.getResourceAsString(
            "${DbConstant.SCHEMA_PATH}/${
                DbTypeUtil.getDbType(dataSource).name.lowercase()
            }/${WorkFlowConstant.SCHEMA_FILE}"
        )?.apply {
            for (sql in this.split(";")) {
                if (sql.trim { it <= ' ' }.length > 10) {
                    sqlUtils.sql(sql).update()
                }
            }
        }
    }

    override fun doInit() {
        val init = Solon.cfg().getBool(DbConstant.INIT_ENABLED_KEY, false)
        if (init) {
            initTable()
        }
    }
}